import { RouteLocationNormalizedLoaded } from 'vue-router'

export interface TagView extends Partial<RouteLocationNormalizedLoaded>{
  title?: string
}

export interface IApp {
    sidebarOpen:boolean // 侧边栏展开折叠  --isCollapse
    visitedViews:Array<TagView>
}

const state: IApp = {
  sidebarOpen: false,
  visitedViews: []
}

const mutations = {
  SET_SIDEBAR_OPEN: (state:IApp) => { // 侧边栏开关
    state.sidebarOpen = !state.sidebarOpen
  },
  SET_TAG_VIEW: (state:IApp, view:TagView) => {
    if (state.visitedViews.some(v => v.path === view.path)) return
    state.visitedViews.push(
      Object.assign({}, view, {
        title: view.meta?.title || 'no-name'
      })
    )
  },
  UPDATE_TAG_VIEW: (state:IApp, view:TagView) => {
    for (let v of state.visitedViews) {
      if (v.path === view.path) {
        v = Object.assign(v, view)
        break
      }
    }
  },
  DEL_TAG_VIEW: (state:IApp, view:TagView) => {
    for (const [i, v] of state.visitedViews.entries()) {
      if (v.path === view.path) {
        state.visitedViews.splice(i, 1)
        break
      }
    }
  }
}

const actions = {
  active_add_tag_view (content:any, view:TagView) {
    content.commit('SET_TAG_VIEW', view)
  },
  active_update_tag_view (content:any, view:TagView) {
    content.commit('UPDATE_TAG_VIEW', view)
  },
  active_delete_tag_view (content:any, view:TagView) {
    content.commit('DEL_TAG_VIEW', view)
  }
}
const getters = {
  get_sidebarOpen: (state:IApp) => state.sidebarOpen,
  get_visitedViews: (state:IApp) => state.visitedViews
}
export const app = {
  namespace: true,
  state,
  mutations,
  actions,
  getters
}
